package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.heima.apis.article.IArticleClient;
import com.heima.apis.comment.ICommentClient;
import com.heima.apis.user.IUserClient;
import com.heima.model.article.dtos.ArticleCommentDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsCommentDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.*;
import com.heima.model.wemedia.vo.CommentRepayListVo;
import com.heima.wemedia.service.WmNewsCommentService;
import com.heima.wemedia.service.WmUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.index.qual.SameLen;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import thread.WmThreadLocalUtil;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsCommentServiceImpl implements WmNewsCommentService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Qualifier("com.heima.apis.article.IArticleClient")
    @Autowired
    private IArticleClient articleClient;

    @Autowired
    private WmUserService wmUserService;

    /**
     * 评论列表
     *
     * @param dto
     * @return
     */
    @Override
    public PageResponseResult findNewsComments(ArticleCommentDto dto) {
        WmUser user = WmThreadLocalUtil.getWmUserThreadLocal();
        dto.setWmUserId(user.getId());
        PageResponseResult newsComments = articleClient.findNewsComments(dto);
        return newsComments;
    }


    /**
     * 查看评论详情
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list(WmNewsCommentDto dto) {
        //参数校验
        if (dto == null || dto.getArticleId() == null) {
            PageResponseResult pageResponseResult = new PageResponseResult();
            pageResponseResult.setCode(501);
            return pageResponseResult;
        }
        //数据处理
        Integer wmUserId = WmThreadLocalUtil.getWmUserThreadLocal().getId();
        Integer authorId = wmUserService.getById(wmUserId).getApAuthorId();
        Query query = Query.query(Criteria.where("authorId").is(authorId).and("entryId").is(dto.getArticleId()));

        query.skip((dto.getPage() - 1) * dto.getSize());
        query.limit(dto.getSize());
//        //查询总记录数
//        long count = mongoTemplate.count(query, WmNewsComment.class);
        //查询该文章的所有评论
        List<WmNewsComment> wmNewsComments = mongoTemplate.find(query, WmNewsComment.class);
        List<String> commentIds = wmNewsComments.stream().map(WmNewsComment::getId).collect(Collectors.toList());
        //遍历评论,获取每一条评论的回复列表
        //data{评论 [回复[]]}
        List<CommentRepayListVo> list = new ArrayList<>();
        for (WmNewsComment wmNewsComment : wmNewsComments) {
            //看当前评论是否被自己点赞:commentLike中存在当前commentID+userID,将comment.operation=0
            List<ApCommentLike> apCommentLikes = mongoTemplate.find(Query.query(Criteria.where("commentId").in(commentIds).and("authorId").is(authorId)), ApCommentLike.class);
            for (ApCommentLike apCommentLike : apCommentLikes) {
                if (wmNewsComment.getId().equals(apCommentLike.getCommentId())) {
                    wmNewsComment.setOperation((short) 0);
                }
            }
            CommentRepayListVo commentRepayListVo = new CommentRepayListVo();
            String wmNewsCommentId = wmNewsComment.getId();
            List<WmNewsCommentRepay> wmNewsCommentRepays = mongoTemplate.find(Query.query(Criteria.where("commentId").is(wmNewsCommentId).and("authorId").is(authorId)), WmNewsCommentRepay.class);
            commentRepayListVo.setApComments(wmNewsComment);
            commentRepayListVo.setApCommentRepays(wmNewsCommentRepays);
            list.add(commentRepayListVo);
        }
        return ResponseResult.okResult(list);
    }

    /**
     * 打开/关闭评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult update_comment_status(WmNewsCommentDto dto) {
        //参数校验
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer id = WmThreadLocalUtil.getWmUserThreadLocal().getId();
        WmUser wmUser = wmUserService.getById(id);
        Integer authorId = wmUser.getApAuthorId();
        //关闭评论前需要清空评论:
        mongoTemplate.remove(Query.query(Criteria.where("authorId").is(authorId).and("entryId").is(dto.getArticleId())), WmNewsComment.class);
        //获取当前作者当篇文章的所有评论
        List<WmNewsComment> wmNewsComments = mongoTemplate.find(Query.query(Criteria.where("entryId").is(dto.getArticleId()).and("authorId").is(id)), WmNewsComment.class);
        for (WmNewsComment wmNewsComment : wmNewsComments) {
            //获取每条评论的回复
            List<WmNewsCommentRepay> commentRepays = mongoTemplate.find(Query.query(Criteria.where("commentId").is(wmNewsComment.getId())), WmNewsCommentRepay.class);
            //获取回复的id
            List<String> repayId = commentRepays.stream().map(WmNewsCommentRepay::getId).collect(Collectors.toList());
            //删除所有关系
            mongoTemplate.remove(Query.query(Criteria.where("authorId").is(id).and("commentId").is(wmNewsComment.getId())), ApCommentLike.class);
            mongoTemplate.remove(Query.query(Criteria.where("authorId").is(id).and("commentId").is(wmNewsComment.getId())), ApCommentRepay.class);
            //删除当前评论回复的like
            mongoTemplate.remove(Query.query(Criteria.where("authorId").is(id).and("commentRepayId").in(repayId)), ApCommentRepay.class);
        }
        return articleClient.update_comment_status(dto);
    }


    /**
     * 评论回复
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult comment_repay(ArticleCommentDto dto) {
        //参数校验
        if (dto == null || StringUtils.isBlank(dto.getCommentId())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer userId = WmThreadLocalUtil.getWmUserThreadLocal().getId();
        if (userId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        WmUser wmUser = wmUserService.getById(userId);
        Integer authorId = wmUser.getApAuthorId();
        String name = wmUser.getName();
        return commentClient.saveCommentRepay(dto, authorId, name);
    }


    @Autowired
    private ICommentClient commentClient;
    /**
     * 点赞评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(ArticleCommentDto dto) {
        //参数校验
        if (dto == null || dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取当前线程id
        Integer wmUserId = WmThreadLocalUtil.getWmUserThreadLocal().getId();
        //通过id获取wmUser对象
        WmUser wmUser = wmUserService.getById(wmUserId);
        if (wmUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //获取当前用户的authorId
        Integer authorId = wmUser.getApAuthorId();
        //通过前端commentId查询该条评论
        return commentClient.commentLike(dto, authorId);
    }

    /**
     * 删除评论
     *
     * @param commentId
     * @return
     */
    @Override
    public ResponseResult del_comment(String commentId) {
        //参数校验
        if (StringUtils.isBlank(commentId)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "评论id不能为空");
        }
        WmNewsComment wmNewsComment = mongoTemplate.findById(commentId, WmNewsComment.class);
        Long articleId = wmNewsComment.getEntryId();
        //删除评论
        mongoTemplate.remove(Query.query(Criteria.where("id").is(commentId)), WmNewsComment.class);
        //article中comment-1
        articleClient.reduceComment(articleId);
        //删除评论回复
        mongoTemplate.remove(Query.query(Criteria.where("commentId").is(commentId)), WmNewsComment.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 删除评论回复
     *
     * @param commentRepayId
     * @return
     */
    @Override
    public ResponseResult delCommentRepay(String commentRepayId) {
        if (StringUtils.isBlank(commentRepayId)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "评论回复id不能为空");
        }
        ApCommentRepay commentRepay = mongoTemplate.findById(commentRepayId, ApCommentRepay.class);
        mongoTemplate.remove(Query.query(Criteria.where("id").is(commentRepayId)), ApCommentRepay.class);
        //comment中repay-1
        String commentId = commentRepay.getCommentId();
        WmNewsComment newsComment = mongoTemplate.findById(commentId, WmNewsComment.class);
        newsComment.setReply(Math.max(newsComment.getReply() - 1, 0));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
